<?php

namespace app\controllers\h5;

use app\controllers\h5\base\H5Controller;
use app\models\SetUserUp;
use app\models\Sms;
use app\models\system\SetApp;
use app\models\system\SetBasic;
use app\models\system\SetFlow;
use app\models\system\SetSms;
use app\models\user\User as Model;
use app\controllers\h5\services\User as Service;
use app\models\user\UserAccount;
use app\models\user\UserCommission;
use app\models\user\UserLevel;
use app\services\Chain;
use app\services\ScoreService;
use app\util\JWT;
use app\util\Util;
use Yii;

/**
 * Class UserController
 * @package app\controllers\h5
 */
class UserController extends H5Controller
{
    /**
     * Login
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionLogin()
    {
        $mobile = $this->post('mobile');
        $password = $this->post('password');

        if (!$mobile || !$password) {
            return $this->fail('请输入正确的用户名或者密码');
        }

        // login
        $user = Service::login($mobile, $password);
        if (!empty($user)) {
            if ($user['status'] == Model::$statusMapping['CLOSE']) {
                return $this->fail('正在关小黑屋中....');
            }

            // login ip
            $user->login_ip = Util::getClientIp();
            $user->save();

            // generate token
            $token = JWT::createToken(
                [
                    'mobile' => $mobile,
                    'id' => $user['id'],
                ],
                Yii::$app->params['JWT_H5_KEY'],
                Yii::$app->params['JWT_H5_EXPIRED']
            );

            return $this->successEncode([
                'token' => $token,
                'id' => $user['id'],
            ], '登录成功');
        }

        return $this->fail('登录失败,请检查手机号码或者密码是否正确');
    }

    public function actionRegister()
    {
        $data = $this->post();

        // check user isExist
        $user = Model::findOne(['mobile' => $data['mobile']]);
        if ($user) {
            return $this->fail('此手机号码已经被注册了');
        }

        // referrer mobile or id
        if (isset($data['referrer']) && $data['referrer']) {
            $referrer = Model::find()
                ->where(['id' => $data['referrer']])
                ->orWhere(['mobile' => $data['referrer']])
                ->one();
            if (!$referrer) {
                return $this->fail('推荐人错误');
            }
            $data['referrer_id'] = $referrer->id;

            // check referrer
            // if (Service::checkReferrer($data['id'], $data['referrer_id'])) {
            //     return $this->fail('推荐人错误!!!');
            // }
        }

        // level
        // $data['level'] = UserLevel::$keys['none'];

        // 注册完成变成会员, 并且送积分
        $data['level'] = UserLevel::$keys['vip1'];
        // register
        $data = ['User' => $data];
        $model = new Model();
        if ($model->load($data) && $model->save()) {
            // user account
            $account = new UserAccount();
            $account->user_id = $model->id;
            if ($account->save()) {

                // 送积分
                $commission = new UserCommission();
                $commission->score = (float) UserLevel::find()
                    ->where(['value' => UserLevel::$keys['vip1']])
                    ->select(['score'])
                    ->scalar();
                $commission->user_id = $account->user_id;
                $commission->award_name = '注册';
                $commission->award_type = 33;
                $commission->status = 1;
                $commission->save();

                $account->score += $commission->score;
                $account->save();

                ScoreService::score($account->user_id, $commission->score);

                // 推荐人也得积分
                $r = Chain::getReferrer($model->id, true);
                if ($r) {
                    $commission = new UserCommission();
                    $score = 0;
                    if ($r->level == UserLevel::$keys['vip3']) {
                        $score = SetUserUp::getLastOne()->vip3_vip1_score;
                    } else if ($r->level == UserLevel::$keys['vip2']) {
                        $score = SetUserUp::getLastOne()->vip2_vip1_score;
                    } else if ($r->level == UserLevel::$keys['vip1']) {
                        $score = SetUserUp::getLastOne()->vip1_vip1_score;
                    }

                    $commission->user_id = $r->id;
                    $commission->award_name = '推荐注册';
                    $commission->award_type = 34;
                    $commission->score = $score;
                    $commission->status = 1;
                    $commission->save();

                    $a = UserAccount::findOne(['user_id' => $r->id]);
                    $a->score += $score;
                    $a->save();

                    ScoreService::score($a->user_id, $score);
                }

                return $this->success('注册成功');
            }
        }


        return $this->fail('注册失败');
    }

    /**
     * Get user info
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionGetInfo()
    {
        $user = Service::getInfo($this->user->id);

        if ($user !== false) {

            // $user['vip1_display'] = UserLevel::find()
            //     ->where(['value' => UserLevel::$keys['vip1']])
            //     ->select(['display'])
            //     ->scalar();
            $user['vip1_display'] = '赠送产品';
            $user['vip2_display'] = UserLevel::find()
                ->where(['value' => UserLevel::$keys['vip2']])
                ->select(['display'])
                ->scalar();

            return $this->successEncode($user);
        }

        return $this->fail('获取用户信息失败');
    }

    /**
     * Register agreement
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionAgreement()
    {
        $model = SetBasic::getLastOne();

        return $this->success($model->agreement);
    }

    /**
     * Get verify code
     *
     * @return array|string[]|\yii\web\Response
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function actionVerifyCode()
    {
        $mobile = $this->post('mobile');
        if (!$mobile) {
            return $this->fail('请输入手机号码');
        }

        $set = SetSms::getLastOne();

        if (Sms::isSend($mobile)) {
            return $this->fail('请' . $set->timeout . '分钟之后再来...');
        }

        $start = pow(10, $set->len - 1);
        $end = pow(10, $set->len) - 1;
        $code = mt_rand($start, $end);
        if (Sms::generateCode($mobile, $code)) {
            $data = ['timeout' => $set->timeout];

            // is simulate
            if ($set->switch == 1) {
                $data['code'] = $code;
            }

            return $this->successEncode($data, '验证码已经成功发送,请注意查收!');
        }

        return $this->fail('获取验证码失败');
    }

    /**
     * Check verify
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionCheckVerify()
    {
        $mobile = $this->post('mobile');
        $code = $this->post('code');

        if (Sms::verify($mobile, $code)) {
            return $this->success();
        }

        return $this->fail('验证码错误');
    }

    /**
     * Forget password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionForgetPassword()
    {
        $data = $this->post();

        $model = Model::findOne(['mobile' => $data['mobile']]);
        if (!$model) {
            return $this->fail('手机号码错误');
        }
        if ($model->status == Model::$statusMapping['CLOSE']) {
            return $this->fail('您已经被拉黑,无法修改');
        }

        $model->password = $data['password'];

        if ($model->save()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    /**
     * Change password
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionChangePassword()
    {
        $data = $this->post();

        if ($data['password'] != $data['password2']) {
            return $this->fail('两次密码不相同');
        }

        if (strlen($data['password']) < 6) {
            return $this->fail('长度不能小于6位');
        }

        $user = Model::findOne(['id' => $this->user->id]);

        if ($data['old_password'] != $user->password) {
            return $this->fail('旧密码错误');
        }

        $user->password = $data['password'];
        if ($user->save()) {
            return $this->success();
        }

        return $this->fail('操作失败');
    }

    /**
     * check wx login open
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionWxLogin()
    {
        $model = SetApp::getLastOne();

        return $this->successEncode($model->open_wx_login);
    }

    /**
     * Is it need referrer
     *
     * @return array|string[]|\yii\web\Response
     */
    public function actionNeedReferrer()
    {
        $model = SetFlow::getLastOne();

        return $this->successEncode($model->register_referrer);
    }

    // 此接口给对方API请求
    // /h5/user/api-user
    // http://api2.ykwhfgs999.com.cn/h5/user/api-user
    public function actionApiUser()
    {
        if (!Yii::$app->request->getIsPost()) {
            return $this->fail('请求方式错误');
        }

        // 设置的
        $key = 'cQAFMXRnbJDtJwfe62FpmRPZNkPH8awD';

        $token = $this->post('token', '');
        $mobile = $this->post('mobile', '');
        $password = $this->post('password', '');
        $referrer = $this->post('referrer', '');

        if (!$token) {
            return $this->fail('token错误');
        }
        if ($token != $key) {
            return $this->fail('token错误22');
        }

        if (!$mobile) {
            return $this->fail('请传递mobile');
        }
        if (!$password) {
            return $this->fail('请传递password');
        }

        $u = Model::find()
            ->where(['mobile' => $mobile])
            ->one();
        if ($u) {
            return $this->fail('mobile已经被注册');
        }

        $referrer_id = 0;
        if ($referrer) {
            $r = Model::find()
                ->where(['mobile' => $referrer])
                ->one();
            if (!$r) {
                return $this->fail('推荐人错误');
            }

            if ($referrer == $mobile) {
                return $this->fail('推荐人错误');
            }

            $referrer_id = $r->id;
        }


        $data = ['User' => [
            'mobile' => $mobile,
            'password' => $password,
            'referrer_id' => $referrer_id,
            // 记录api请求
            'is_api_request' => 1,
            // 注册就有等级
            'level' => UserLevel::$keys['vip1'],
        ]];

        $transaction = \Yii::$app->db->beginTransaction();
        try {
            $model = new Model();
            if ($model->load($data) && $model->save()) {
                // user account
                $account = new UserAccount();
                $account->user_id = $model->id;
                if ($account->save()) {

                    // 送积分
                    $commission = new UserCommission();
                    $commission->score = (float)UserLevel::find()
                        ->where(['value' => UserLevel::$keys['vip1']])
                        ->select(['score'])
                        ->scalar();
                    $commission->user_id = $account->user_id;
                    $commission->award_name = '注册';
                    $commission->award_type = 33;
                    $commission->status = 1;
                    $commission->save();

                    $account->score += $commission->score;
                    $account->save();

                    ScoreService::score($account->user_id, $commission->score);

                    // 推荐人也得积分
                    $r = Chain::getReferrer($model->id, true);
                    if ($r) {
                        $commission = new UserCommission();
                        $score = 0;
                        if ($r->level == UserLevel::$keys['vip3']) {
                            $score = SetUserUp::getLastOne()->vip3_vip1_score;
                        } else if ($r->level == UserLevel::$keys['vip2']) {
                            $score = SetUserUp::getLastOne()->vip2_vip1_score;
                        } else if ($r->level == UserLevel::$keys['vip1']) {
                            $score = SetUserUp::getLastOne()->vip1_vip1_score;
                        }

                        $commission->user_id = $r->id;
                        $commission->award_name = '推荐注册';
                        $commission->award_type = 34;
                        $commission->score = $score;
                        $commission->status = 1;
                        $commission->save();

                        $a = UserAccount::findOne(['user_id' => $r->id]);
                        $a->score += $score;
                        $a->save();

                        ScoreService::score($a->user_id, $score);
                    }

                    $transaction->commit();
                    return $this->success('注册成功');
                } else {
                    throw new \Exception('注册失败2');
                }
            } else {
                throw new \Exception('注册失败1');
            }
        } catch (\Exception $e) {
            $transaction->rollBack();
            return $this->fail($e->getMessage());
        }


        return $this->success('测试成功');
    }
}